import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 懒加载组件
const Home = () => import('@/views/home/ConsultEntry.vue')
const ConsultChat = () => import('@/views/chat/ConsultChat.vue')
const DepartmentRecommend = () => import('@/views/department/DepartmentRecommend.vue')
const MedicalRecord = () => import('@/views/record/MedicalRecord.vue')
const Login = () => import('@/views/auth/Login.vue')
const Register = () => import('@/views/auth/Register.vue')
const QueueQuery = () => import('@/views/other/QueueQuery.vue')
const HospitalMap = () => import('@/views/other/HospitalMap.vue')
const EmotionCare = () => import('@/views/other/EmotionCare.vue')

// 路由配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 首页'
      }
    },
    {
      path: '/consult',
      name: 'consult',
      component: ConsultChat,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 智能问诊'
      }
    },
    {
      path: '/department-recommend',
      name: 'departmentRecommend',
      component: DepartmentRecommend,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 科室推荐'
      }
    },
    {
      path: '/medical-record/:id?',
      name: 'medicalRecord',
      component: MedicalRecord,
      meta: {
        requiresAuth: true,
        title: '医联智导 - 病历详情'
      }
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 登录'
      }
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 注册'
      }
    },
    {
      path: '/queue',
      name: 'queue',
      component: QueueQuery,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 排队查询'
      }
    },
    {
      path: '/map',
      name: 'map',
      component: HospitalMap,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 院内导航'
      }
    },
    {
      path: '/emotion-care',
      name: 'emotionCare',
      component: EmotionCare,
      meta: {
        requiresAuth: false,
        title: '医联智导 - 情感关怀'
      }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const isLoggedIn = authStore.isLoggedIn
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !isLoggedIn) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else {
    next()
  }
})

export default router
